package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.tzbb.*;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.service.algs.TzbbUploadService;
import com.app.utils.Base64Util;
import com.app.utils.HttpClients;
import com.app.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 东郊质控平台通途
 */
@Slf4j
@RestController
@RequestMapping("/tzbb")
public class TzbbUploadController {
    @Value("${yj.tzbb.getpublickey}")
    private String getpublickey;
    @Value("${yj.tzbb.desservices}")
    private String desservices;
    @Value("${yj.tzbb.rsaservices}")
    private String rsaservices;
    @Value("${yj.tzbb.uploadresultdata}")
    private String uploadresultdata;
    @Value("${yj.tzbb.uploadrawdata}")
    private String uploadrawdata;
    @Value("${yj.tzbb.account}")
    private String account;
    @Value("${yj.tzbb.password}")
    private String password;
    @Value("${yj.tzbb.company}")
    private String company;
    @Value("${yj.tzbb.deskey}")
    private String deskey;
    @Value("${yj.tzbb.accountverify}")
    private String accountverify;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    TzbbUploadService tzbbUploadService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException, UnsupportedEncodingException {
        ExternalResponse externalResponse = null;
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");


            Publickey publickey = (Publickey) JSON.parseObject(StringUtil.replaceBlank(HttpClients.requestTokenPost(getpublickey)), Publickey.class);
            Map<String, Object> param = new HashMap<>();
            param.put("task", "getenc_text");
            param.put("plain_text", password);
            param.put("deskey", deskey);
            Desserve desserve = (Desserve) JSON.parseObject(StringUtil.replaceBlank(HttpClients.doGet(desservices, param)), Desserve.class);
            param.clear();
            param.put("task", "getenc_text");
            param.put("plain_text", deskey);
            param.put("public_key", publickey.getPublickey());
            Rsaserve rsaserve = (Rsaserve) JSON.parseObject(StringUtil.replaceBlank(HttpClients.doGet(rsaservices, param)), Rsaserve.class);
            String account_base64 = Base64Util.encode(account);
            param.clear();
            param.put("account", account_base64);
            param.put("password", desserve.getEnc_text());
            param.put("deskey", rsaserve.getEnc_text());
            Accountverify account = (Accountverify) JSON.parseObject(StringUtil.replaceBlank(HttpClients.doGet(accountverify, param)), Accountverify.class);
            if (account != null) {
                List<YjData> yjDataList = yjDataService.findList(ids);
                List<List<YjData>> groupList = new ArrayList<>();
                yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
                    groupList.add(yjDataGroupList);
                });
                UploadParameter uploadParameter = uploadParameterService.findOne("24");
                for (List<YjData> yjData : groupList) {
                    List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
                    Uploadresultdata tzbbData = tzbbUploadService.getTzbbData(yjData, uploadParameter, account);
                    String s = JSON.toJSONString(tzbbData);
                    Map<String, String> map = new HashMap<>();
                    map.put("token", account.getAccess_token());
                    String s1 = StringUtil.generateParams(map, "utf-8");
                    String result = HttpClients.requestPost(uploadresultdata + "?" + s1, s);
                    if (result.startsWith("\uFEFF")) {
                        result = result.substring(2);
                    }
                    System.out.println(result);
                    DataResult dataResult = JSON.parseObject(result, DataResult.class);
                    if (StringUtils.isNotEmpty(dataResult.getNBeamID()) && StringUtils.isNotEmpty(dataResult.getSBeamCode())) {
                        int i = 0;
                        List<Uploadrawdata> drawList = tzbbUploadService.getDraw(tzbbData, yjData, dataResult);
                        for (Uploadrawdata drawdata : drawList) {
                            map.clear();
                            map.put("token", account.getAccess_token());
                            map.put("nbeamid", dataResult.getNBeamID());
                            map.put("ngroorder", String.valueOf(drawdata.getNGroOrder()));
                            map.put("ssteelcode", drawdata.getSSteelCode());
                            String ss = JSON.toJSONString(drawdata);
                            String s2 = StringUtil.generateParams(map, "utf-8");
                            String result1 = HttpClients.requestPost(uploadrawdata + "?" + s2, ss);
                            if (result1.contains("\"returncode\":\"00\"")) {
                                i++;
                            }
                        }
                        if (i == drawList.size()) {
                            for (Integer userId : userIds) {
                                updateState("1", String.valueOf(userId));
                                succTotal++;
                            }
                        } else {
                            for (Integer userId : userIds) {
                                updateState("0", String.valueOf(userId));
                                failTotal++;
                            }
                        }
                       /* for (Integer userId : userIds) {
                            updateState("1", String.valueOf(userId));
                            succTotal++;
                        }*/
                    } else {
                        for (Integer userId : userIds) {
                            updateState("0", String.valueOf(userId));
                            failTotal++;
                        }
                    }

            }

        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }

    public static void main(String[] args) {
//        JSON.parseObject("\uFEFF\uFEFF{\"nBeamID\":\"289217\",\"sBeamCode\":\"cs1\"}");
        String s = "\uFEFF\uFEFF{\"nBeamID\":\"289217\",\"sBeamCode\":\"cs1\"}";
        String substring = s.substring(2);
        String ss = "";
        System.out.println(substring);
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}